package com.tj.ocr.img;

import java.awt.image.BufferedImage;

import com.tj.ocr.similar.Project;

public class LinePop {

	private static final int full_height = 14;
	// private static final int space_height = 4;

	private BufferedImage img;
	private int[][] imageData;
	private int[] lineData;
	private int pos_fromy = 0;

	private int width = 0;
	private int height = 0;

	public LinePop(MyImage img) {
		this.img = img.getImage();
		this.imageData = img.getData();
		this.lineData = img.getData_line();
		this.width = this.img.getWidth();
		this.height = this.img.getHeight();
		this.pos_fromy = img.getFromy();
	}

	private int getStartPosY(int from) {
		for (int i = from; i < height; i++) {
			if(this.lineData[i] ==1)
				return i;
			/*if (hasDataY(i)) {;
				return i;
			}*/
		}

		return -1;
	}

	@SuppressWarnings("unused")
    private boolean hasDataY(int index) {
		for (int i = 0; i < width; i++) {
			if (imageData[i][index] == 1)
				return true;
			// System.out.println(img.getRGB(index, i));
			if (Project.isBlank(img.getRGB(i, index))) {
				// System.out.println(1);
				return true;
			}

			/*
			 * if(img.getRGB(i, index) == blank) return true;
			 */
		}

		return false;
	}

	public static void init() {
	}

	/*
	 * 1. get textArea 2. do ocr 3. goto next 3.1 全角 / 半角
	 */
	public MyImage pop() {
		pos_fromy = getStartPosY(pos_fromy);
		if (pos_fromy == -1)
			return null;

		int from = pos_fromy;// , to = from + full_height;
		int to = getEndPos(pos_fromy);
		if (to >= height)
			return null;

		// full reg
		MyImage ret = new MyImage(this.img, this.imageData, 0, from, width, to - from);

		// ImageRW.write(ret.realImage(), "d:\\test\\tt\\tr3 "+is+".jpg");

		pos_fromy += (to - from + 1);

		return ret;
	}

	private int getEndPos(int pos_from) {
		for (int y = pos_from + full_height; y < img.getHeight(); y++) {
			//if (! hasDataY(y))
			if(this.lineData[y] == 0)
				return y;
		}
		
		return img.getHeight() + 1;
	}

	public static void main(String[] args) {
		BufferedImage sbi = ImageRW.read("d:\\test\\tt.png");
		LinePop pop = new LinePop(BlankWhiteUtil.procEx(sbi, 170));
		MyImage mi = null;
		int is = 0;
		while ((mi = pop.pop()) != null) {
			ImageRW.write(mi.realImage(), "d:\\test\\tt\\tr3 "+(is++)+".jpg");
			
			TextPop pops = new TextPop(mi);
			while (pops.pop() != null) {
			}

		}
	}
}
